from django.db import models
from mdeditor.fields import MDTextField #必须导入

# Create your models here.

class APIInfo(models.Model):
    """API Model"""
    # 接口名称
    api_name = models.CharField(max_length=32, verbose_name="接口名称", default="请输入接口名称")
    # 接口描述
    api_describe = models.TextField(max_length=255, verbose_name="接口描述", default="请输入接口描述")

    # 接口负责人
    api_manager = models.CharField(max_length=11, verbose_name="接口负责人", default="请输入接口负责人名字")

    # 创建时间
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    # 修改时间
    update_time = models.DateTimeField(auto_now=True, blank=True, null=True, verbose_name="修改时间")

    class Meta:
        # db_table = 'api_info'
        # 设置表名，默认表名是：应用名称_模型类名
        # 带有应用名的表名太长了
        verbose_name = '接口列表'
        verbose_name_plural = "接口列表"

    def __str__(self):
        return self.api_name


class UserInfo(models.Model):
    """用户信息表"""
    username = models.CharField(verbose_name="用户名", max_length=32, db_index=True)  # db_index=True创建索引
    password = models.CharField(verbose_name="密码", max_length=32)
    email = models.EmailField(verbose_name="邮箱", max_length=32)
    mobile_phone = models.CharField(verbose_name="手机号码", max_length=32)
    project_num = models.IntegerField(verbose_name="已创建项目数量", default=0)

    # price_policy = models.ForeignKey(verbose_name="价格策略", to='PricePolicy',
    #                                  on_delete=models.DO_NOTHING, null=True, blank=True )


class PricePolicy(models.Model):
    """价格策略表"""
    category_choices = (
        (1, "免费版"),
        (2, "收费版"),
        (3, "其他"),
    )
    category = models.SmallIntegerField(verbose_name="收费类型", choices=category_choices,
                                        default=2)  # SmallIntegerField 范围小一些的整型
    title = models.CharField(verbose_name="标题", max_length=32)
    price = models.PositiveIntegerField(verbose_name="价格")  # PositiveIntegerField正整数类型

    project_num = models.PositiveIntegerField(verbose_name="项目数")
    project_member = models.PositiveIntegerField(verbose_name="成员数")
    project_space = models.PositiveIntegerField(verbose_name="单项目空间大小")
    per_file_size = models.PositiveIntegerField(verbose_name="单文件大小（M）")

    create_datetime = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)


class Transaction(models.Model):
    """交易记录表"""
    status_choice = (
        (1, '未支付'),
        (2, '已支付')
    )
    status = models.SmallIntegerField(verbose_name="状态", choices=status_choice)

    order = models.CharField(verbose_name="订单号", max_length=64, unique=True)  # 唯一索引 unique=True
    user = models.ForeignKey(verbose_name="用户", to='UserInfo', on_delete=models.DO_NOTHING)
    price_policy = models.ForeignKey(verbose_name="价格策略", to='PricePolicy', on_delete=models.DO_NOTHING)

    count = models.IntegerField(verbose_name="数量（年）", help_text="0表示无期限")

    price = models.IntegerField(verbose_name="实际支付价格")

    start_datetime = models.DateTimeField(verbose_name="开始时间", null=True, blank=True)
    end_datetime = models.DateTimeField(verbose_name="结束时间", null=True, blank=True)

    create_datetime = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)


class Project(models.Model):
    """项目表"""
    COLOR_CHOICES = (
        (1, "#56b8eb"),
        (2, "#f28033"),
        (3, "#ebc656"),
        (4, "#a2d148"),
        (5, "#20BFA4"),
        (6, "#7461c2"),
        (7, "#20bfa3"),
    )

    name = models.CharField(verbose_name="项目名称", max_length=32)
    color = models.SmallIntegerField(verbose_name="状态", choices=COLOR_CHOICES, default=1)
    desc = models.CharField(verbose_name="项目描述", max_length=255, null=True, blank=True)
    use_space = models.BigIntegerField(verbose_name="项目已使用空间", default=0)
    star = models.BooleanField(verbose_name="星标", default=False)
    bucket = models.CharField(verbose_name="桶名称", max_length=128)
    region = models.CharField(verbose_name="桶区域", max_length=64)

    join_count = models.SmallIntegerField(verbose_name="参与人数", default=1)
    creator = models.ForeignKey(verbose_name="创建者", to='UserInfo', on_delete=models.DO_NOTHING)
    create_datetime = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)


class ProjectUser(models.Model):
    """项目参与者表"""
    user = models.ForeignKey(verbose_name="参与者", to='UserInfo', on_delete=models.DO_NOTHING)
    project = models.ForeignKey(verbose_name="项目", to='Project', on_delete=models.DO_NOTHING)

    # 当一张表的两个字段关联的外键相同时，需要用related_name=""修改其中一个字段在反向关联时使用的名称
    # 获取一个用户对象obj = UserInfo.objects.filter(id=1)
    # 在ProjectUser表中添加用户表的外键语法：obj.projectuser_set.all()
    # 在使用related_name="invites"后会变成obj.invites.all(),这样就能有效的防止相同外键同名（都使用projectuser_set）的问题
    # invitee = models.ForeignKey(verbose_name="邀请者", to='UserInfo', related_name="invites", null=True, blank=True)  #

    star = models.BooleanField(verbose_name="星标", default=False)

    create_datetime = models.DateTimeField(verbose_name="加入时间", auto_now_add=True)


class Wiki(models.Model):
    """wiki表"""
    project = models.ForeignKey(verbose_name="项目", to='Project', on_delete=models.DO_NOTHING)
    title = models.CharField(verbose_name="标题", max_length=32)
    content = models.TextField(verbose_name="内容")
    # 深度 初始值为1
    depth = models.IntegerField(verbose_name="深度", default=1)

    # 自关联
    parent = models.ForeignKey(verbose_name="父文章", to='Wiki', on_delete=models.SET_NULL, related_name='children',
                               null=True, blank=True)
    create_datetime = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)

    def __str__(self):
        return self.title


class FileRepository(models.Model):
    project = models.ForeignKey(verbose_name="项目", to='Project', on_delete=models.CASCADE)
    file_name = models.CharField(verbose_name="文件名称", max_length=128, help_text="文件夹/文件名称")
    # 如果是文件夹，是没有cos桶名称的，所以key值空域为空
    key_name = models.CharField(verbose_name="cos存储桶内对应文件的key", max_length=128, null=True, blank=True)
    file_type_choices = (
        (1, "文件"),
        (2, "文件夹")
    )
    file_type = models.SmallIntegerField(verbose_name="类型", choices=file_type_choices, default=2)  # 1是文件夹，2是文件
    file_size = models.BigIntegerField(verbose_name="文件大小KB", null=True, blank=True)
    file_path = models.CharField(verbose_name="文件路径", max_length=255, null=True, blank=True)  # cos桶内文件的直接下载路径
    parent = models.ForeignKey(verbose_name="父目录", to='FileRepository', on_delete=models.CASCADE,
                               related_name='child', null=True, blank=True)

    # 文件记录创建者的信息
    create_user = models.ForeignKey(verbose_name="创建者", to='UserInfo', on_delete=models.DO_NOTHING,
                                    related_name="create")
    create_datetime = models.DateTimeField(verbose_name="创建时间", auto_now_add=True)
    # 文件记录的修改这的信息
    update_user = models.ForeignKey(verbose_name="更新者", to='UserInfo', on_delete=models.DO_NOTHING,
                                    related_name="update")
    update_datetime = models.DateTimeField(verbose_name="更新时间", auto_now_add=True)


class Issues(models.Model):
    """
    问题
    """
    project = models.ForeignKey(verbose_name='所属项目', to='Project', on_delete=models.CASCADE)
    issues_type = models.ForeignKey(verbose_name='问题类型', to='IssuesType', on_delete=models.DO_NOTHING)

    module = models.ForeignKey(verbose_name='所属模块', to='Module', null=True, blank=True, on_delete=models.DO_NOTHING)

    subject = models.CharField(verbose_name='标题', max_length=80, default='【】')
    desc = models.TextField(verbose_name='描述')

    # 问题优先级
    priority_choices = (
        ('danger', '高'),
        ('waring', '中'),
        ('success', '低'),
    )
    priority = models.CharField(verbose_name='优先级', max_length=12,
                                choices=priority_choices, default='waring')

    # 问题状态
    status_choices = (
        (1, '激活'),
        (2, '确认'),
        (3, '已解决'),
        (4, '关闭'),
    )
    status = models.SmallIntegerField(verbose_name='当前状态', choices=status_choices, default=1)

    # 指派给，由于指派给、关注者都外键于用户表，需要添加related_name字段进行区分
    assign = models.ForeignKey(verbose_name='当前指派', to='UserInfo', related_name='task', on_delete=models.DO_NOTHING)
    # 关注者, ManyToManyField会自动创建一张表用于保存多对多关系
    attention = models.ManyToManyField(verbose_name='关注者', to='UserInfo', related_name='observe', blank=True)

    # 开始和结束时间
    start_datetime = models.DateTimeField(verbose_name="开始时间", null=True, blank=True)
    end_time = models.DateTimeField(verbose_name="结束时间", null=True, blank=True)

    mode_choices = (
        (1, '公开模式'),
        (2, '隐私模式'),
    )

    mode = models.SmallIntegerField(verbose_name='模式', choices=mode_choices, default=1)
    parent = models.ForeignKey(verbose_name='父问题', to='self', related_name='child',
                               null=True, blank=True, on_delete=models.SET_NULL)

    creator = models.ForeignKey(verbose_name='创建者', to='UserInfo', related_name='create_problems',
                                on_delete=models.DO_NOTHING)
    create_datetime = models.DateTimeField(verbose_name="开始时间", auto_now_add=True)
    latest_update_datetime = models.DateTimeField(verbose_name="开始时间", auto_now=True)

    # 打印对象时，返回问题的标题
    def __str__(self):
        return self.subject


class Module(models.Model):
    """
    问题的模块
    """
    project = models.ForeignKey(verbose_name='所属项目', to='Project', on_delete=models.CASCADE)
    title = models.CharField(verbose_name='模块名称', max_length=32)

    # 打印对象时，返回模块的名称
    def __str__(self):
        return self.title


class IssuesType(models.Model):
    """
    问题的类型：任务、功能、Bug
    """
    title = models.CharField(verbose_name='类型名称', max_length=32)
    project = models.ForeignKey(verbose_name='所属项目', to='Project', on_delete=models.CASCADE)

    # 打印对象时，返回类型的名称
    def __str__(self):
        return self.title
